#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
import cgi
import json
import db_conf
import time
import urllib
con = None

#metabolomics_dev=# insert into ntfd_sample_groups (labelfree_group, label_group) values (36, 37);
#INSERT 0 1
#metabolomics_dev=# insert into sample_group_tracer (tracer_id, relative_tracer_amount, sample_group) values (1, 100, 37);

def post_tracer_group(cur, tracer_id, relative_tracer_amount, sample_group):
    try:
        cur.execute("""insert into sample_group_tracer (tracer_id, relative_tracer_amount, sample_group) values (%s, %s, %s) RETURNING 1""", (tracer_id, relative_tracer_amount, sample_group))
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:
        print 'Error Adding new trace sample group %s' % e

def post_ntfd_group(cur, sample_group, labelfree_group):
    try:        
        cur.execute("""insert into ntfd_sample_groups (labelfree_group, label_group) values (%s, %s) RETURNING ntfd_groups_id""", (labelfree_group, sample_group))
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:
        print 'Error Adding new ntfd group %s' % e

def reset_tracer_ntfd(cur, sample_group_list):
    try:
        #str(x) for x in list_of_ints
        join_params = ",".join("%s" for a in sample_group_list)
        sample_group_tuple = tuple(sample_group_list)
        cur.execute("""delete from ntfd_sample_groups where label_group in (""" + join_params + """)""", ( sample_group_tuple))
        cur.execute("""delete from sample_group_tracer where sample_group in (""" + join_params + """)""", ( sample_group_tuple))
        return 1   
    except psycopg2.DatabaseError, e:
        print 'Error Reseting tracer ntfd groups %s' % e
        return -1

def post_update_groups(cur, grp_name, desc, regex, sample_type_id, strain_id, experiment_id, sample_group_id):
    try:
        cur.execute("""update sample_group set (name, description, regex, bio_sample_type_id, strain_id, experiment_id) = (%s, %s, %s, %s, %s, %s) where sample_group_id = %s  RETURNING sample_group_id""", (grp_name, desc, regex, sample_type_id, strain_id, experiment_id, sample_group_id))
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:
        print 'Adding new sample group error %s' % e
try:
    qform = cgi.FieldStorage()
    exp_ops = qform.getvalue("tracer_ops")
    active_experiment = qform.getvalue("active_experiment")
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    exp_id = ""
    pa = {}
    exp_grps = []
    #exp_ops=delete_tracer_grps&sample_grps=203%2C204
    if (exp_ops != None and exp_ops == "insert_tracer_grps"):
        grp_rows = qform.getvalue("tracer_rows")        
        for i in range(0, int(grp_rows)):
            sample_grp = qform.getvalue('sample_group' + str(i))
            tracer_id = qform.getvalue('sample_tracer' + str(i))
            tracer_amount = qform.getvalue('tracer_amount' + str(i))
            labelfree_grp = qform.getvalue('ntfd_grp' + str(i))
            if (labelfree_grp != None and labelfree_grp != "NA"):
                spid = post_ntfd_group(cur, sample_grp, labelfree_grp)
            if (tracer_id != None and tracer_id != ""):
                spid = post_tracer_group(cur, tracer_id, tracer_amount, sample_grp)
    if (exp_ops != None and exp_ops == "delete_tracer_grps"):
        sample_grps = qform.getvalue('sample_grps')
	#sample_grp_list = urllib.unquote(sample_grps).decode('utf8').split(",")
        sample_grp_list = sample_grps.split(",")
        reset_tracer_ntfd(cur, sample_grp_list)
    cur.execute("commit")
    pa['_status'] = "200"
    print "Content-type: text/html;charset=utf-8\r\n"    
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Update Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()

